//
//  GFunView.m
//  guess
//
//  Created by fank on 15/11/7.
//  Copyright © 2015年 fank. All rights reserved.
//

#import "GFunView.h"
#import "Define.h"
#import <SVProgressHUD/SVProgressHUD.h>
//#import "MultilevelMenu.h"
#import <UIKit/UIKit.h>
#import "GHttpEnqine.h"
#import "YouYiSiSingleDataModel.h"
#import "GFunTVC.h"
#import "PhotoBroswerVC.h"


@interface GFunView()<UITableViewDelegate,UITableViewDataSource>
{
    int page;
}
//@property MultilevelMenu * menuView;
@property UITableView * messageTableView;

@property NSMutableArray * dataArr;

@end


@implementation GFunView

-(instancetype)initWithFrame:(CGRect)frame
{
    self =[super initWithFrame:frame];

    //集成刷新控件
//    [self addHeader];
//    [self addFooter];
//    [self setTheMenu];
    self.messageTableView =[[UITableView alloc]initWithFrame:CGRectMake(0, frame.origin.y, frame.size.width, frame.size.height) style:UITableViewStylePlain];
    [self addSubview:self.messageTableView];
    self.messageTableView.delegate = self;
    self.messageTableView.dataSource = self;
    self.messageTableView.separatorStyle =UITableViewCellSeparatorStyleNone;
    self.backgroundColor = UIColorFromRGBValue(0xDBE0E4);
    //集成刷新控件
    [self addHeader];
    [self addFooter];

    [self getDataWith:page withWay:0];
    return self;
}

-(void)getData
{
    
}
//-(void)setTheMenu
//{
//    NSMutableArray * lis=[NSMutableArray arrayWithCapacity:0];
//    
//    
//    /**
//     *  构建需要数据 2层或者3层数据 (ps 2层也当作3层来处理)
//     */
//    NSInteger countMax=6;
//    for (int i=0; i<countMax; i++) {
//        
//        rightMeun * meun=[[rightMeun alloc] init];
//        meun.meunName=[NSString stringWithFormat:@"菜单%d",i];
//        NSMutableArray * sub=[NSMutableArray arrayWithCapacity:0];
//        for ( int j=0; j <countMax+1; j++) {
//            
//            rightMeun * meun1=[[rightMeun alloc] init];
//            meun1.meunName=[NSString stringWithFormat:@"%d头菜单%d",i,j];
//            
//            [sub addObject:meun1];
//            
//            //meun.meunNumber=2;
//            
//            NSMutableArray *zList=[NSMutableArray arrayWithCapacity:0];
//            if (j%2==0) {
//                
//                for ( int z=0; z <countMax+2; z++) {
//                    
//                    rightMeun * meun2=[[rightMeun alloc] init];
//                    meun2.meunName=[NSString stringWithFormat:@"%d层菜单%d",j,z];
//                    
//                    [zList addObject:meun2];
//                    
//                }
//            }
//            
//            meun1.nextArray=zList;
//        }
//        
//        
//        meun.nextArray=sub;
//        [lis addObject:meun];
//    }
    
    /**
     *  适配 ios 7 和ios 8 的 坐标系问题
     */
//    self.automaticallyAdjustsScrollViewInsets=NO;
    
    /**
     默认是 选中第一行
     
     :returns: <#return value description#>
     */
//    NSString *urlString = @"http://www.u148.net/list/";
//    
//    MultilevelMenu * menuView=[[MultilevelMenu alloc] initWithFrame:CGRectMake(0, 0, kscreenWith-20, kscreenHeight-64) WithUrl:urlString withSelectIndex:^(NSInteger left, NSInteger right,rightMeun* info) {
//        
//        NSLog(@"点击的 菜单%@",info.meunName);
//    }];
//    
//    
////    menuView.needToScorllerIndex=0;
//    
//    menuView.isRecordLastScroll=YES;
//    [self addSubview:menuView];
//}


- (void)addHeader
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加下拉刷新头部控件
    
    self.messageTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        page = 1;
        [vc getDataWith:page withWay:0];
    }];
    [self.messageTableView.header beginRefreshing];
}

- (void)addFooter
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加上拉刷新尾部控件
    self.messageTableView.footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        page +=1;
        [vc getDataWith:page withWay:1];
    }];
}



#pragma  mark - data Source 
-(void)getDataWith:(int)pageInt withWay:(int)way
{
    NSNumber * pageNum =[NSNumber numberWithInt:pageInt];
    NSLog(@"%@",pageNum);
    NSString * url =@"http://www.u148.net/list/";
    [GHttpEnqine getYouYiSiPicWithUrl:url page:pageNum success:^(id data) {
        [self.messageTableView.header endRefreshing];
        [self.messageTableView.footer endRefreshing];
        NSLog(@"%@",data);
        if (way ==1) {
            for (NSDictionary *dict in (NSMutableArray *)[data objectForKey:@"info"]) {
                [_dataArr addObject:dict];
            }
        }else{
            _dataArr =[NSMutableArray array];
            for (NSDictionary *dict in (NSMutableArray *)[data objectForKey:@"info"]) {
                [_dataArr addObject:dict];
            }
        }
        
        
        [self.messageTableView reloadData];
    } fail:^(id error) {
        [self.messageTableView.header endRefreshing];
        [self.messageTableView.footer endRefreshing];
        [SVProgressHUD showErrorWithStatus:error];
    }];
}




#pragma mark -tableViewDelegate

-(NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArr count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        YouYiSiSingleDataModel *singleData =[YouYiSiSingleDataModel modelWithDictionary:_dataArr[indexPath.row] error:nil];
        GFunTVC *cell = [[GFunTVC alloc]initWithData:singleData];
//        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        cell.backgroundColor = UIColorFromRGBValue(0xDBE0E4);
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
        __weak typeof(cell) weakCell=cell;
        cell.ClickImageBlock= ^(YouYiSiSingleDataModel * singleImageData){
        
        //本地图片展示
        //            [self localImageShow:index];
        
        //展示网络图片
        [self networkImageShow:indexPath withSingleImageData:singleImageData withTheCell:weakCell];
    };
    
    
    
        [self configureCell:cell atIndexPath:indexPath];
        return cell;

    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

        YouYiSiSingleDataModel *singleData =[YouYiSiSingleDataModel modelWithDictionary:_dataArr[indexPath.row] error:nil];
        
        UIImage *img = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey: singleData.imageUrl];
        if (!img) {
            img = [UIImage imageNamed:@"placehold"];
        }
        CGSize size = [GFunTVC heightWithImage:img];
        CGFloat height = size.height/size.width*(kscreenWith-20);
        return height+90;

}


- (void)configureCell:(GFunTVC *)cell atIndexPath:(NSIndexPath *)indexPath
{
    // 正常的设置文字和其他内容
    YouYiSiSingleDataModel *singleData =[YouYiSiSingleDataModel modelWithDictionary:_dataArr[indexPath.row] error:nil];
    // 开始加载图片
    NSString *imgURL = singleData.imageUrl;    // 图片 url
    UIImage *cachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imgURL];
    
    // 没有已经下载好的图片
    if ( !cachedImage ) {
        // 要是当前 table view 没有在被拖动或者自由滑行
        if ( !self.messageTableView.dragging && !self.messageTableView.decelerating ) {
            // 下载当前 cell 中的图片
            [self downloadImage:imgURL forIndexPath:indexPath];
        }
        // cell 中图片先用缓存的占位图代替
        [cell setSpitslotImage:[UIImage imageNamed:@"placehold"]];
    } else {
        // 找到了缓存的图片，直接插缓存的图片
        [cell setSpitslotImage:cachedImage];
    }
}


- (void)downloadImage:(NSString *)imageURL forIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) target = self;
    // 利用 SDWebImage 框架提供的功能下载图片
    [[SDWebImageDownloader sharedDownloader]downloadImageWithURL:[NSURL URLWithString: imageURL] options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
    } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
        // 保存图片
        [[SDImageCache sharedImageCache] storeImage:image forKey:imageURL toDisk:YES]; // 别忘了保存到磁盘上
        
        // 延迟在主线程更新 cell 的高度
        [target performSelectorOnMainThread:@selector(reloadCellAtIndexPath:)       // 至于这步的原因是为了防止刷的太快了崩溃
                                 withObject:indexPath waitUntilDone:NO];            // 这步会把 selector 的调用放到主线程的 run loop 里排队
    }];
}

- (void)loadImageForOnScreenRows
{
    NSArray *visiableIndexPathes = [self.messageTableView indexPathsForVisibleRows];
    
    for(NSInteger i = 0; i < [visiableIndexPathes count]; i++)
    {
        YouYiSiSingleDataModel *singleData =[YouYiSiSingleDataModel modelWithDictionary:_dataArr[i] error:nil];
        NSString *imgURL = singleData.imageUrl;
        [self downloadImage:imgURL forIndexPath:visiableIndexPathes[i]];
    }
}

- (void)reloadCellAtIndexPath:(NSIndexPath *)indexPath
{
    [self.messageTableView reloadData];
}

#pragma mark - Scroll view delegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    // table view 停止拖动了
    if (!decelerate) {
        [self loadImageForOnScreenRows];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // table view 停止滚动了
        [self loadImageForOnScreenRows];
    
}

#pragma mark - show image delegate
/*
 *  展示网络图片
 */
-(void)networkImageShow:(NSIndexPath *)indexPath withSingleImageData:(YouYiSiSingleDataModel *)singleImageDataModel withTheCell:(GFunTVC *)cell{
    
    [PhotoBroswerVC show:self.selfVC type:PhotoBroswerVCTypeZoom index:indexPath.row photoModelBlock:^NSArray *{
        
        NSMutableArray *modelsM = [NSMutableArray arrayWithCapacity:_dataArr.count];
        for (NSUInteger i = 0; i< _dataArr.count; i++) {
            YouYiSiSingleDataModel *singleData =[YouYiSiSingleDataModel modelWithDictionary:_dataArr[i] error:nil];
            PhotoModel *pbModel=[[PhotoModel alloc] init];
            pbModel.mid = i + 1;
            
            pbModel.title = [NSString stringWithFormat:@"%@            %@",@(i+1),singleData.date];
            pbModel.desc = [NSString stringWithFormat:@"%@",singleData.title];
            pbModel.image_HD_U = singleData.imageUrl;
            
            
            //源frame
            
            GFunTVC *fCell = [self.messageTableView cellForRowAtIndexPath:indexPath];
            UIImageView *imageV =(UIImageView *)fCell.imageImg;
            pbModel.sourceImageView = imageV;
            
            [modelsM addObject:pbModel];
        }
        
        return modelsM;
    }];
}


@end
